package com.nodecollege.cloud.controller.admin;

import com.nodecollege.cloud.common.UpmsConstants;
import com.nodecollege.cloud.common.annotation.ApiAnnotation;
import com.nodecollege.cloud.common.model.LoginAdmin;
import com.nodecollege.cloud.common.model.NCResult;
import com.nodecollege.cloud.common.model.vo.LoginVO;
import com.nodecollege.cloud.service.AdminLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @author LC
 * @date 2019/12/1 12:10
 */
@RestController
@RequestMapping("/admin/login")
public class AdminLoginController {

    @Autowired
    private AdminLoginService adminLoginService;

    /**
     * 管理员登陆
     *
     * @param loginVO
     */
    @ApiAnnotation(modularName = "管理员登陆", description = "管理员登陆")
    @PostMapping("/login")
    public NCResult<String> login(@RequestBody LoginVO loginVO, HttpServletResponse response) {
        LoginAdmin loginAdmin = adminLoginService.login(loginVO);
        Cookie accessTokenCookie = new Cookie(UpmsConstants.HEADER_ACCESS_TOKEN_ADMIN, loginAdmin.getAccessToken());
        accessTokenCookie.setMaxAge(loginAdmin.getExpire().intValue());
        accessTokenCookie.setPath("/");
        Cookie infoRandomCookie = new Cookie(UpmsConstants.HEADER_INFO_RANDOM_ADMIN, loginAdmin.getInfoRandom());
        infoRandomCookie.setMaxAge(loginAdmin.getExpire().intValue());
        infoRandomCookie.setPath("/");
        response.addCookie(accessTokenCookie);
        response.addCookie(infoRandomCookie);
        return NCResult.ok(loginAdmin);
    }

    /**
     * 管理员注册
     *
     * @param loginVO
     */
    @ApiAnnotation(modularName = "管理员登陆", description = "管理员注册")
    @PostMapping("/register")
    public NCResult register(@RequestBody LoginVO loginVO) {
        adminLoginService.register(loginVO);
        return NCResult.ok();
    }

    /**
     * 获取管理员信息
     *
     * @param loginVO
     */
    @ApiAnnotation(modularName = "管理员登陆", description = "获取管理员信息")
    @PostMapping("/getAdminInfo")
    public NCResult<LoginAdmin> getAdminInfo(@RequestBody LoginVO loginVO) {
        LoginAdmin loginAdmin = adminLoginService.getAdminInfo(loginVO.getToken());
        return NCResult.ok(loginAdmin);
    }

    /**
     * 退出登陆
     *
     * @param loginVO
     * @return
     */
    @ApiAnnotation(modularName = "管理员登陆", description = "退出登陆")
    @RequestMapping("/logout")
    public NCResult logout(@RequestBody LoginVO loginVO) {
        adminLoginService.logout(loginVO.getToken());
        return NCResult.ok();
    }

}
